<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkRoom\Queue;

use EasyWeChat\Work\Application;
use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Corp\Utils\WeWorkFactory;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkRoom\Logic\SyncLogic;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * 企业微信-同步微信客户群列表
 * Class SyncListQueue.
 */
class SyncDetailQueue
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var CorpContract
     */
    private $corpService;

    /**
     * @var WorkEmployeeContract
     */
    private $workEmployeeService;

    /**
     * @var WeWorkFactory
     */
    private $weWorkFactory;

    /**
     * @var Application
     */
    private $weWorkApp;

    /**
     * @var LoggerFactory
     */
    private $loggerFactory;

    /**
     * TODO 全量同步时未对比群删除.
     *
     * @AsyncQueueMessage(pool="room")
     * @param int $corpId 企业授信ID
     * @param string $wxRoom 微信群id ['chat_id' => '', 'status' => 0]
     */
    public function handle(int $corpId, array $wxRoom): void
    {
        $this->loggerFactory = $this->container->get(LoggerFactory::class);
        $this->logger = $this->loggerFactory->get(__CLASS__);
        $this->corpService = $this->container->get(CorpContract::class);
        $this->workEmployeeService = $this->container->get(WorkEmployeeContract::class);
        $this->weWorkFactory = $this->container->get(WeWorkFactory::class);

        try {
            $this->logger->debug(sprintf('同步客户群详情开始，企业ID:[%s]，群聊ID:[%s]', (string) $corpId, $wxRoom['chat_id']));
            $this->weWorkApp = $this->weWorkFactory->getContactApp($corpId);

            // 获取群聊详情
            $roomResult = $this->weWorkApp->external_contact->getGroupChat($wxRoom['chat_id']);

            if ($roomResult['errcode'] != 0) {
                $this->logger->error(sprintf('%s [%s] 请求数据：%s 响应结果：%s', '请求企业微信客户群详情错误', date('Y-m-d H:i:s'), $wxRoom['chat_id'], Json::encode($roomResult)));
                return;
            }

            if (empty($roomResult['group_chat'])) {
                return;
            }

            $roomResult['group_chat']['status'] = $wxRoom['status'];

            make(SyncLogic::class)->handle($corpId, $roomResult['group_chat']);
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('同步客户群详情失败，错误消息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
